package com.mtung.dubbo.register;

import org.I0Itec.zkclient.ZkClient;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @author : zhenguo.yao
 * @date : 2020/3/23 0023 10:14
 */
public class ServiceRegisterImpl implements ServiceRegister{

    /**
     * zk连接地址
     */
    private final String zkServers = "127.0.0.1";
    /**
     * 会话时间
     */
    private final int connectionTimeout = 5000;
    /***
     * zkClient
     */
    private ZkClient zkClient;

    private String rootNamePath = "/mtung_rpc";

    public ServiceRegisterImpl() {
        // 1. 连接zk连接
        zkClient = new ZkClient(zkServers, connectionTimeout);
    }

    /**
     * 注册服务信息到zk
     * @param serviceName
     * @param serviceAddress
     * @throws UnsupportedEncodingException
     */
    public void register(String serviceName, String serviceAddress) throws UnsupportedEncodingException {
        // 创建根路径
        if(!zkClient.exists(rootNamePath)){
            zkClient.createPersistent(rootNamePath);
        }
        // 创建接口路径(/mtung_rpc/com.mtung.dubbo.service.UserService)
        String serviceNodePath = rootNamePath + "/" + serviceName;
        if(!zkClient.exists(serviceNodePath)){
            zkClient.createPersistent(serviceNodePath);
        }
        // 创建提供者地址(/mtung_rpc/com.mtung.dubbo.service.UserService/providers)
        String providerNodePath = serviceNodePath + "/" + "providers";
        if(!zkClient.exists(providerNodePath)){
            zkClient.createPersistent(providerNodePath);
        }
        // 创建服务地址mtung://192.168.3.213:8080/com.mtung.dubbo.service.UserService getUser
        String serviceAddressNodePath = providerNodePath + "/" + URLEncoder.encode(serviceAddress);
        System.out.println("serviceAddressNodePath:" + serviceAddressNodePath);
        if (zkClient.exists(serviceAddressNodePath)) {
            zkClient.delete(serviceAddressNodePath);
        }
        zkClient.createEphemeral(serviceAddressNodePath);

    }



}
